package org.springblade.modules.admin.task.feishu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import org.springblade.common.enums.FeiShuDocumentEnum;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.feishu.FeiShuBatchDTO;
import org.springblade.modules.admin.dto.feishu.FeiShuFieldsDTO;
import org.springblade.modules.admin.dto.feishu.FeiShuUpdateFieldsDTO;
import org.springblade.modules.admin.service.BuildingService;
import org.springblade.modules.admin.service.feishu.IFeiShuDocumentService;
import org.springblade.modules.admin.vo.feishu.GalaxyMaintainCustomerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xxl.job.core.handler.annotation.XxlJob;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author: Sharry
 * @createTime: 2024-03-15 9:10
 * @version: Version-1.0
 */
@Component
public class GalaxyMaintainCustomerJob {

	@Autowired
	private IFeiShuDocumentService feiShuDocumentService;

	@Autowired
	private BuildingService buildingService;

	/**
	 * 定时任务：每天 2 点 25 分执行一次
	 * 更新银河维保客户信息_副本 V1
	 */
	@XxlJob("testUpdateMaintainCustomerV1")
	public void testUpdateMaintainCustomerV1() {
		XxlJobHelper.handleSuccess("飞书银河维保客户信息-[执行]开始");
		try {
			// 0. 数据准备：各变量、目标文件夹Token、文档ID、获取银河维保客户信息
			// 0.1 消息返回值等需要提前定义的变量、飞书通用字段
			String messageResult = "";
			// 0.2 目标文件夹Token、文档id
			String appToken = FeiShuDocumentEnum.MAINTENANCE_CUSTOMER_INFORMATION_COPY.getAppToken();
			String tableId = FeiShuDocumentEnum.MAINTENANCE_CUSTOMER_INFORMATION_COPY.getTableId();
			// 0.3 获取银河维保客户信息
			List<GalaxyMaintainCustomerVO> maintainCustomerList = buildingService.getGalaxyMaintainCustomerList();
			// 1. 现有梯无忧银河维保客户信息数据封装
			FeiShuBatchDTO batchDTO = new FeiShuBatchDTO();
			List<FeiShuFieldsDTO> records = new ArrayList<>();
			for (GalaxyMaintainCustomerVO g : maintainCustomerList) {
				FeiShuFieldsDTO element = new FeiShuFieldsDTO();
				Map<String, Object> elementMap = new HashMap<>(10);
				elementMap.put("id", String.valueOf(g.getBuildingId()));
				elementMap.put("坐标地址", g.getLocationAddress());
				elementMap.put("联系人", g.getContactsName());
				elementMap.put("手机号", g.getContactPhone());
				elementMap.put("项目名称", g.getBuildingName());
				elementMap.put("类型", g.getBuildingType());
				elementMap.put("使用单位", g.getUseUnit());
				elementMap.put("梯数", g.getElevatorNum());
				element.setFields(elementMap);
				records.add(element);
			}
			// 2. id 作为key 执行对比更新
			batchDTO.setRecords(records);
			messageResult = feiShuDocumentService.commandCompareUpdateBatch(appToken,tableId,batchDTO,"id");
			// 3. 发送消息
			// 3.1 获取目标群组
			List<JSONObject> targetGroupObjects = feiShuDocumentService.commandQueryGroupsBatch();
			List<String> chatIds = new ArrayList<>();
			targetGroupObjects.forEach(t -> chatIds.add(t.getString("chat_id")));
			// 3.2 所有群组均发送消息
			String finalResult = messageResult;
			chatIds.forEach(c -> {
				// 组装数据
				JSONObject bodyJson = new JSONObject();
				bodyJson.put("receive_id", c);
				bodyJson.put("msg_type", "text");
				HashMap<String, String> contentMap = new HashMap<>(2);
				String message = "更新"+ FeiShuDocumentEnum.getDescription(appToken,tableId) +"，结果：" + finalResult;
				message += "\n 飞书list接口版本：V1";
				contentMap.put("text", message);
				// 将 contentMap 转换成 JSON 格式
				bodyJson.put("content", JSON.toJSONString(contentMap));
				feiShuDocumentService.commandSendGroupMessage(bodyJson.toJSONString());
			});
			XxlJobHelper.handleSuccess("飞书银河排期表副本-[执行]成功");
		} catch (Exception e) {
			XxlJobHelper.handleFail("飞书银河维保客户信息-[执行]失败");
		}
	}


	/**
	 * 定时任务：每天 2 点 28 分执行一次
	 * 更新银河维保客户信息_副本 V2
	 * 时间复杂度：O(n^2)
	 */
	@XxlJob("testUpdateMaintainCustomerV2")
	public void testUpdateMaintainCustomerV2() {
		XxlJobHelper.handleSuccess("飞书银河维保客户信息-[执行]开始");
		try {
			// 0. 数据准备：各变量、目标文件夹Token、文档ID、获取银河维保客户信息、飞书通用字段
			// 0.1 消息返回值等需要提前定义的变量
			String messageResult = "更新" + FeiShuDocumentEnum.MAINTENANCE_CUSTOMER_INFORMATION_COPY.getDescription() + "\n";
			// 0.2 需要新增的数据、需要更新的数据、需要删除的数据
			List<FeiShuFieldsDTO> needAdd = new ArrayList<>();
			List<FeiShuUpdateFieldsDTO> needUpdate = new ArrayList<>();
			List<String> needDelete = new ArrayList<>();
			// 0.3 目标文件夹Token、文档id
			String appToken = FeiShuDocumentEnum.MAINTENANCE_CUSTOMER_INFORMATION_COPY.getAppToken();
			String tableId = FeiShuDocumentEnum.MAINTENANCE_CUSTOMER_INFORMATION_COPY.getTableId();
			// 0.4 获取银河维保客户信息
			List<GalaxyMaintainCustomerVO> maintainCustomerList = buildingService.getGalaxyMaintainCustomerList();
			// 1. 数据封装、获取现有表格数据
			// 1.1 获取现有表格数据，根据 text 类型 的 id 进行id提取，作为更新数据的标准，且要加入record_id
			List<Map<String, String>> keyMap = feiShuDocumentService.commandGetTextKeys(appToken, tableId, null, "id");
			// 2. 数据处理、数据比对
			// 2.1 比对需要删除的数据：现有数据中，但是新数据中没有的数据
			for (Map<String, String> m : keyMap) {
				Set<Map.Entry<String, String>> entries = m.entrySet();
				String key = "";
				AtomicReference<String> keyRef = new AtomicReference<>(key);
				entries.forEach(e -> keyRef.set(e.getKey()));
				String finalKey = keyRef.get();
				boolean isExist = false;
				for (GalaxyMaintainCustomerVO g : maintainCustomerList) {
					if (m.containsKey((g.getBuildingId()))) {
						isExist = true;
						break;
					}
				}
				if (!isExist) {
					needDelete.add(m.get(finalKey));
				}
			}
			// 2.2 比对需要新增的数据：新数据中有，但是现有数据中没有的数据
			for (GalaxyMaintainCustomerVO galaxyMaintainCustomerVO : maintainCustomerList) {
				boolean isExist = false;
				for (Map<String, String> m : keyMap) {
					Set<Map.Entry<String, String>> entries = m.entrySet();
					String key = "";
					AtomicReference<String> keyRef = new AtomicReference<>(key);
					entries.forEach(e -> keyRef.set(e.getKey()));
					String finalKey = keyRef.get(); // 获取最终的key值

					if (galaxyMaintainCustomerVO.getBuildingId().equals(finalKey)) {
						isExist = true;
						// 存在则说明该条数据需要更新
						FeiShuUpdateFieldsDTO element = new FeiShuUpdateFieldsDTO();
						Map<String, Object> elementMap = new HashMap<>(10);
						elementMap.put("id", galaxyMaintainCustomerVO.getBuildingId());
						elementMap.put("坐标地址", galaxyMaintainCustomerVO.getLocationAddress());
						elementMap.put("联系人", galaxyMaintainCustomerVO.getContactsName());
						elementMap.put("手机号", galaxyMaintainCustomerVO.getContactPhone());
						elementMap.put("项目名称", galaxyMaintainCustomerVO.getBuildingName());
						elementMap.put("类型", galaxyMaintainCustomerVO.getBuildingType());
						elementMap.put("使用单位", galaxyMaintainCustomerVO.getUseUnit());
						elementMap.put("梯数", galaxyMaintainCustomerVO.getElevatorNum());
						element.setFields(elementMap);
						element.setRecord_id(m.get(finalKey));
						needUpdate.add(element);
						break;
					}
				}
				if (!isExist) {
					FeiShuFieldsDTO element = new FeiShuFieldsDTO();
					Map<String, Object> elementMap = new HashMap<>(10);
					elementMap.put("id", galaxyMaintainCustomerVO.getBuildingId());
					elementMap.put("坐标地址", galaxyMaintainCustomerVO.getLocationAddress());
					elementMap.put("联系人", galaxyMaintainCustomerVO.getContactsName());
					elementMap.put("手机号", galaxyMaintainCustomerVO.getContactPhone());
					elementMap.put("项目名称", galaxyMaintainCustomerVO.getBuildingName());
					elementMap.put("类型", galaxyMaintainCustomerVO.getBuildingType());
					elementMap.put("使用单位", galaxyMaintainCustomerVO.getUseUnit());
					elementMap.put("梯数", galaxyMaintainCustomerVO.getElevatorNum());
					element.setFields(elementMap);
					needAdd.add(element);
				}
			}
			// 3. 根据比对结果，更新、删除、新增数据
			// 3.1 删除数据
			if (!Func.isEmpty(needDelete)) {
				FeiShuBatchDTO tempFeiShuBatchDTO = new FeiShuBatchDTO();
				tempFeiShuBatchDTO.setRecords(needDelete);
				messageResult += "删除" + needDelete.size() + "条数据，结果：";
				messageResult += feiShuDocumentService.commandDeleteBatchLimit(appToken, tableId, tempFeiShuBatchDTO) + "\n";

			}
			// 3.2 新增数据，调用 commandAddBatchLimit
			if (!Func.isEmpty(needAdd)) {
				FeiShuBatchDTO tempFeiShuBatchDTO = new FeiShuBatchDTO();
				tempFeiShuBatchDTO.setRecords(needAdd);
				messageResult += "新增" + needAdd.size() + "条数据, 结果：";
				messageResult += feiShuDocumentService.commandAddBatchLimit(appToken, tableId, tempFeiShuBatchDTO) + "\n";
			}
			// 3.3 更新数据，调用 commandUpdateBatchLimit
			if (!Func.isEmpty(needUpdate)) {
				FeiShuBatchDTO tempFeiShuBatchDTO = new FeiShuBatchDTO();
				tempFeiShuBatchDTO.setRecords(needUpdate);
				messageResult += "更新" + needUpdate.size() + "条数据,结果：";
				messageResult += feiShuDocumentService.commandUpdateBatchLimit(appToken, tableId, tempFeiShuBatchDTO) + "\n";
			}
			messageResult += "飞书list接口版本：V2";
			// 4. 发送消息
			feiShuDocumentService.commandSendGroupMessage(appToken, tableId, messageResult);
			XxlJobHelper.handleSuccess("飞书银河排期表副本-[执行]成功");
		} catch (Exception e) {
			XxlJobHelper.handleFail("飞书银河维保客户信息-[执行]失败");
		}
	}

	/**
	 * 定时任务：每天 2 点 25 分执行一次
	 * 更新银河维保客户信息
	 */
	@XxlJob("updateMaintainCustomerV1")
	public void updateMaintainCustomerV1() {
		XxlJobHelper.handleSuccess("飞书银河维保客户信息-[执行]开始");
		try {
			// 0. 数据准备：各变量、目标文件夹Token、文档ID、获取银河维保客户信息
			// 0.1 消息返回值等需要提前定义的变量、飞书通用字段
			String messageResult = "";
			// 0.2 目标文件夹Token、文档id
			String appToken = FeiShuDocumentEnum.MAINTENANCE_CUSTOMER_INFORMATION.getAppToken();
			String tableId = FeiShuDocumentEnum.MAINTENANCE_CUSTOMER_INFORMATION.getTableId();
			// 0.3 获取银河维保客户信息
			List<GalaxyMaintainCustomerVO> maintainCustomerList = buildingService.getGalaxyMaintainCustomerList();
			// 1. 现有梯无忧银河维保客户信息数据封装
			FeiShuBatchDTO batchDTO = new FeiShuBatchDTO();
			List<FeiShuFieldsDTO> records = new ArrayList<>();
			for (GalaxyMaintainCustomerVO g : maintainCustomerList) {
				FeiShuFieldsDTO element = new FeiShuFieldsDTO();
				Map<String, Object> elementMap = new HashMap<>(10);
				elementMap.put("id", String.valueOf(g.getBuildingId()));
				elementMap.put("坐标地址", g.getLocationAddress());
				elementMap.put("联系人", g.getContactsName());
				elementMap.put("手机号", g.getContactPhone());
				elementMap.put("项目名称", g.getBuildingName());
				elementMap.put("类型", g.getBuildingType());
				elementMap.put("使用单位", g.getUseUnit());
				elementMap.put("梯数", g.getElevatorNum());
				element.setFields(elementMap);
				records.add(element);
			}
			// 2. id 作为key 执行对比更新
			batchDTO.setRecords(records);
			messageResult = feiShuDocumentService.commandCompareUpdateBatch(appToken,tableId,batchDTO,"id");
			// 3. 发送消息
			// 3.1 获取目标群组
			List<JSONObject> targetGroupObjects = feiShuDocumentService.commandQueryGroupsBatch();
			List<String> chatIds = new ArrayList<>();
			targetGroupObjects.forEach(t -> chatIds.add(t.getString("chat_id")));
			// 3.2 所有群组均发送消息
			String finalResult = messageResult;
			chatIds.forEach(c -> {
				// 组装数据
				JSONObject bodyJson = new JSONObject();
				bodyJson.put("receive_id", c);
				bodyJson.put("msg_type", "text");
				HashMap<String, String> contentMap = new HashMap<>(2);
				String message = "更新"+ FeiShuDocumentEnum.getDescription(appToken,tableId) +"，结果：" + finalResult;
				message += "\n 飞书list接口版本：V1";
				contentMap.put("text", message);
				// 将 contentMap 转换成 JSON 格式
				bodyJson.put("content", JSON.toJSONString(contentMap));
				feiShuDocumentService.commandSendGroupMessage(bodyJson.toJSONString());
			});
			XxlJobHelper.handleSuccess("飞书银河排期表副本-[执行]成功");
		} catch (Exception e) {
			XxlJobHelper.handleFail("飞书银河维保客户信息-[执行]失败");
		}
	}

}
